//
//  DownloadView.m
//  ebook
//
//  Created by ChenNan on 16/4/20.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "DownloadView.h"
#import "DownloadManager.h"
#import "UIImage+RTTint.h"
#import "ReaderGlobalModel.h"
#import "MTRotatingScreen.h"

@interface DownloadView ()

@property (nonatomic, strong) ReaderConfig *readerConfig;
@property (nonatomic, assign) DownloadType downtype;
@property (nonatomic, strong) NSMutableArray *btnsArray;//保存可选的章节按钮：10章， 100章...
@property (nonatomic) float width;

@end

@implementation DownloadView

- (instancetype)initWithReaderConfig:(ReaderConfig *)config {
    
    if (isIpad) {
        _width = 320 + 60;
    } else {
        _width = MTScreenW;
    }
    self = [super initWithFrame:CGRectMake(0, 0, _width, 140)];
    
    if (self) {
        _btnsArray = [NSMutableArray array];
        _readerConfig = config;
        if(_readerConfig.DownloadType == 0)
            _readerConfig.DownloadType = Download_all;
        _downtype = _readerConfig.DownloadType;
        [self drawView];
    }
    return self;
}

-(void)setIsNight:(BOOL)isNight{
    _isNight = isNight;
}

- (void)drawView {
    
    float edgeLeft = 20;
    if ([MTRotatingScreen isOrientationLandscape]) {
        edgeLeft = _width/6;
    }
    
    float width = (_width-2*edgeLeft)/3;
    
    float height = 40;
    NSArray *array_title = @[@"后续10章", @"后续100章", @"后续500章", @"后续1000章", @"后续章节", @"全本缓存"];
    UIImage *selectedImage = [[UIImage imageNamed:@"dianxuan_sl"] rt_tintedImageWithColor:MTConfigColor(_isNight?@"MTReaderBar_NightSelected_Color":@"MTReaderBar_DaySelected_Color")];
    for (int i = 0; i < array_title.count; i++) {
        NSInteger row = i/3, col = i%3;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(edgeLeft + width * col, 10 + row * height, width, height);
        btn.titleLabel.font = [UIFont systemFontOfSize:MTScreenW>320?14.0:12.0];
        [btn setImage:[UIImage imageNamed:@"dianxuan_nl"] forState:UIControlStateNormal];
        [btn setImage:selectedImage forState:UIControlStateSelected];
        [btn setTitleColor:MTConfigColor(@"MTReaderToolBar_textTint_Color") forState:UIControlStateNormal];
        [btn setTitle:array_title[i] forState:UIControlStateNormal];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        switch (i) {
            case 0:
                btn.tag = Download_10;
                break;
            case 1:
                btn.tag = Download_100;
                break;
            case 2:
                btn.tag = Download_500;
                break;
            case 3:
                btn.tag = Download_1000;
                break;
            case 4:
                btn.tag = Download_nowToEnd;
                break;
            case 5:
                btn.tag = Download_all;
                break;
                
            default:
                break;
        }
    
        btn.selected = btn.tag==_readerConfig.DownloadType;
        [btn addTarget:self action:@selector(btn_selectedItem:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        [_btnsArray addObject:btn];
    }
    
    UIButton *downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    downloadBtn.frame = CGRectMake(edgeLeft, 100, _width-edgeLeft*2, 40);
    [downloadBtn setTitle:@"开始下载" forState:UIControlStateNormal];
    [downloadBtn setTitleColor:MTConfigColor(@"MTReaderToolBar_downloadBtnNormal_Color") forState:UIControlStateNormal];
    [downloadBtn setTitleColor:MTConfigColor(@"MTReaderToolBar_downloadBtnNormal_Color") forState:UIControlStateHighlighted];
    UIColor *dbborderColor = MTConfigColor(@"MTReaderToolBar_downloadBtnBorder_Color");
    downloadBtn.layer.borderColor = dbborderColor.CGColor;
    downloadBtn.layer.borderWidth = 1.0f;
    downloadBtn.layer.cornerRadius = 3.0f;
    downloadBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [downloadBtn addTarget:self action:@selector(downloadTask) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:downloadBtn];
    [self addSubview:_downloadBtn];
    _downloadBtn = downloadBtn;
    
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(_downloadBtn.x, CGRectGetMinY(_downloadBtn.frame)+_downloadBtn.height/2, _downloadBtn.width-70, _downloadBtn.height)];
    [self addSubview:progressView];
    progressView.trackTintColor = MTConfigColor(@"MTReaderToolBar_downloadProgressViewTint_Color");
    progressView.hidden = YES;
    [self addSubview:progressView];
    _progressView = progressView;
    
    UILabel *waitLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(progressView.frame)+10, _width, 20)];
    waitLabel.text = @"等待下载中...";
    waitLabel.font = [UIFont systemFontOfSize:12.0];
    waitLabel.textAlignment = NSTextAlignmentCenter;
    waitLabel.textColor = MTConfigColor(@"MTReaderToolBar_downloadWaitLabelText_Color");
    waitLabel.hidden = YES;
    [self addSubview:waitLabel];
    _waitLabel = waitLabel;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(_downloadBtn.x+CGRectGetWidth(_downloadBtn.frame)-50, _downloadBtn.y, 50, _downloadBtn.height);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:MTConfigColor(@"MTReaderToolBar_downloadCancelBtnTitle_Color") forState:UIControlStateNormal];
    UIColor *cancelBtnBorderColor = MTConfigColor(@"MTReaderToolBar_downloadCancelBtnBorder_Color");
    [cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.layer.borderColor = cancelBtnBorderColor.CGColor;
    cancelBtn.layer.borderWidth = 1.0f;
    cancelBtn.layer.cornerRadius = 3.0f;
    cancelBtn.hidden = YES;
    [self addSubview:cancelBtn];
    _cancelBtn = cancelBtn;
}

-(void)setDownloadType:(DownloadType)type{

    if(type != 0) _downtype = type;
    for (UIButton *btn0 in _btnsArray) {
        btn0.selected = btn0.tag==_downtype;
    }
}

#pragma mark - 选择下载章节内容
- (void)btn_selectedItem:(UIButton *)btn {
    
    _downtype = (DownloadType)btn.tag;
    
    for (UIButton *btn0 in _btnsArray) {
        btn0.selected = btn0.tag==_downtype;
    }
}

#pragma mark - 点击开始下载按钮
- (void)downloadTask{
    
    for (UIButton *btn in _btnsArray) {//开始下载，进度条显示，按钮不可以被点击
        btn.userInteractionEnabled = NO;
    }
    //进度条设置默认值，（否则，先显示蓝色，再灰色，进度＋＋）
    _progressView.progress = 0.0f;
    if ([self.delegate respondsToSelector:@selector(downloadView:downloadType:)]) {
        [self.delegate downloadView:self downloadType:_downtype];
    }
}

-(void)cancelBtnClick{
    
    for (UIButton *btn in _btnsArray) {
        btn.userInteractionEnabled = YES;
    }
    
    if ([self.delegate respondsToSelector:@selector(downloadView:downloadCancel:)]) {
        [self.delegate downloadView:self downloadCancel:YES];
    }
}

//显示下载按钮状态
-(void)downloadState{
    
    _progressView.hidden = YES;
    _cancelBtn.hidden = YES;
    _downloadBtn.hidden = NO;
    _waitLabel.hidden = YES;
    for (UIButton *btn in _btnsArray) {
        btn.userInteractionEnabled = YES;
    }
}

//显示进度状态
-(void)progressState{
    
    _progressView.hidden = NO;
    _cancelBtn.hidden = NO;
    _downloadBtn.hidden = YES;
    _waitLabel.hidden = YES;
}

//显示下载等待状态
-(void)showWaitingStatus {
    
    _downloadBtn.hidden = YES;
    _progressView.hidden = NO;
    _cancelBtn.hidden = NO;
    _waitLabel.hidden = NO;
}

- (void)setProgressPercent:(float)percent exist:(BOOL)exist{
    
    if (exist||percent>=1) {
        
        [self downloadState];
        for (UIButton *btn in _btnsArray) { //选择章节按钮恢复可以点击
            btn.userInteractionEnabled = YES;
        }
    } else {
        
        [self progressState];
        [_progressView setProgress:percent animated:YES];
    }
}


@end
